<script setup>
import { ref, reactive, onMounted } from 'vue'

const userInfo = ref(null)
const isPremium = ref(false)
const showUpgradePrompt = ref(false)
const currentCategory = ref('physiological')

// 评估类别
const assessmentCategories = [
  { id: 'physiological', name: '基本生理评估' },
  { id: 'psychological', name: '精神心理评估' },
  { id: 'lifestyle', name: '生活自理能力' },
  { id: 'physical', name: '基本运动能力' },
  { id: 'social', name: '社会参与度' }
]

// 基本生理评估项目
const physiologicalItems = [
  { id: 'bone', name: '骨骼', score: 0, description: '骨骼支撑功能、关节灵活度' },
  { id: 'skin', name: '皮肤', score: 0, description: '皮肤弹性、光泽、湿润度' },
  { id: 'brain', name: '脑', score: 0, description: '记忆力、思维清晰度、反应能力' },
  { id: 'lymph', name: '淋巴', score: 0, description: '免疫功能、排毒能力' },
  { id: 'cardiopulmonary', name: '心肺', score: 0, description: '心肺功能、气血运行' },
  { id: 'hepatobiliary', name: '肝胆', score: 0, description: '肝胆功能、疏泄能力' },
  { id: 'spleen', name: '脾胃', score: 0, description: '消化吸收功能、运化能力' },
  { id: 'intestine', name: '大小肠', score: 0, description: '肠道蠕动、排泄功能' },
  { id: 'excretion', name: '二便', score: 0, description: '大小便规律性与质量' }
]

// 精神心理评估项目
const psychologicalItems = [
  { id: 'emotion', name: '情绪状态', score: 0, description: '情绪稳定性、喜怒哀乐平衡' },
  { id: 'stress', name: '压力应对', score: 0, description: '面对压力的调节能力' },
  { id: 'sleep', name: '睡眠质量', score: 0, description: '入睡难易度、睡眠深度、醒后状态' },
  { id: 'anxiety', name: '焦虑水平', score: 0, description: '担忧、紧张程度' },
  { id: 'mood', name: '心情愉悦度', score: 0, description: '乐观积极的心态' }
]

// 生活自理评估项目
const lifestyleItems = [
  { id: 'eating', name: '饮食能力', score: 0, description: '独立进食、安排饮食能力' },
  { id: 'dressing', name: '穿衣能力', score: 0, description: '独立穿脱衣物能力' },
  { id: 'hygiene', name: '个人卫生', score: 0, description: '清洁、洗漱能力' },
  { id: 'toilet', name: '如厕能力', score: 0, description: '独立如厕能力' },
  { id: 'medication', name: '服药管理', score: 0, description: '按时按量服药能力' }
]

// 基本运动评估项目
const physicalItems = [
  { id: 'walking', name: '步行能力', score: 0, description: '行走稳定性、持续时间' },
  { id: 'balance', name: '平衡能力', score: 0, description: '站立、转身平衡性' },
  { id: 'flexibility', name: '柔韧性', score: 0, description: '关节活动范围、肌肉伸展性' },
  { id: 'strength', name: '肌肉力量', score: 0, description: '主要肌群力量' },
  { id: 'endurance', name: '耐力', score: 0, description: '持续活动能力' }
]

// 社会参与评估项目
const socialItems = [
  { id: 'communication', name: '沟通能力', score: 0, description: '语言表达、理解能力' },
  { id: 'relationships', name: '人际关系', score: 0, description: '与家人、朋友互动质量' },
  { id: 'activities', name: '社会活动', score: 0, description: '参与社区活动频率' },
  { id: 'interests', name: '兴趣爱好', score: 0, description: '维持个人兴趣爱好' },
  { id: 'support', name: '社会支持', score: 0, description: '获取社会支持的能力' }
]

// 所有评估项目
const assessmentItems = {
  physiological: physiologicalItems,
  psychological: psychologicalItems,
  lifestyle: lifestyleItems,
  physical: physicalItems,
  social: socialItems
}

// 总分和评级
const totalScore = ref(0)
const maxScore = ref(0)
const assessmentLevel = ref('')
const assessmentResults = reactive({
  physiological: { completed: false, score: 0, maxScore: physiologicalItems.length * 10 },
  psychological: { completed: false, score: 0, maxScore: psychologicalItems.length * 10 },
  lifestyle: { completed: false, score: 0, maxScore: lifestyleItems.length * 10 },
  physical: { completed: false, score: 0, maxScore: physicalItems.length * 10 },
  social: { completed: false, score: 0, maxScore: socialItems.length * 10 }
})

// 评分标准
const scoreOptions = [
  { value: 0, label: '未评估' },
  { value: 2, label: '很差' },
  { value: 4, label: '较差' },
  { value: 6, label: '一般' },
  { value: 8, label: '良好' },
  { value: 10, label: '优秀' }
]

onMounted(() => {
  // 获取用户信息
  const storedUserInfo = uni.getStorageSync('userInfo')
  if (storedUserInfo) {
    userInfo.value = storedUserInfo
    isPremium.value = ['standard', 'premium'].includes(storedUserInfo.membershipLevel)
    
    // 如果不是高级会员，只显示部分评估功能
    if (!isPremium.value) {
      showUpgradePrompt.value = true
    }
    
    // 计算最大可能分数
    calculateMaxScore()
  } else {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/login/index'
      })
    }, 1500)
  }
})

function switchCategory(categoryId) {
  currentCategory.value = categoryId
}

function updateScore(categoryId, itemId, score) {
  // 查找并更新对应项目的分数
  const items = assessmentItems[categoryId]
  const item = items.find(i => i.id === itemId)
  if (item) {
    item.score = score
    
    // 更新分类的总分
    updateCategoryScore(categoryId)
  }
}

function updateCategoryScore(categoryId) {
  const items = assessmentItems[categoryId]
  const totalCategoryScore = items.reduce((sum, item) => sum + item.score, 0)
  
  // 更新分类评估结果
  assessmentResults[categoryId].score = totalCategoryScore
  assessmentResults[categoryId].completed = !items.some(item => item.score === 0)
  
  // 更新总分
  calculateTotalScore()
}

function calculateTotalScore() {
  let sum = 0
  let completed = true
  
  // 计算所有分类的总分
  Object.values(assessmentResults).forEach(result => {
    sum += result.score
    if (!result.completed) {
      completed = false
    }
  })
  
  totalScore.value = sum
  
  // 根据总分计算健康等级
  if (completed) {
    const percentage = (sum / maxScore.value) * 100
    
    if (percentage >= 90) {
      assessmentLevel.value = '优秀'
    } else if (percentage >= 80) {
      assessmentLevel.value = '良好'
    } else if (percentage >= 70) {
      assessmentLevel.value = '中等'
    } else if (percentage >= 60) {
      assessmentLevel.value = '一般'
    } else {
      assessmentLevel.value = '需要改善'
    }
  } else {
    assessmentLevel.value = '未完成'
  }
}

function calculateMaxScore() {
  let max = 0
  
  // 计算所有分类的最大可能分数
  Object.values(assessmentResults).forEach(result => {
    max += result.maxScore
  })
  
  maxScore.value = max
}

function saveAssessmentResults() {
  // 判断是否完成所有评估
  const isCompleted = !Object.values(assessmentResults).some(result => !result.completed)
  
  if (!isCompleted) {
    uni.showModal({
      title: '提示',
      content: '您还有未完成的评估项目，确定要保存吗？',
      success: function(res) {
        if (res.confirm) {
          performSave()
        }
      }
    })
  } else {
    performSave()
  }
}

function performSave() {
  // 保存评估结果
  const assessmentData = {
    date: new Date().toISOString(),
    userInfo: userInfo.value.username,
    totalScore: totalScore.value,
    maxScore: maxScore.value,
    assessmentLevel: assessmentLevel.value,
    categories: JSON.parse(JSON.stringify(assessmentResults)),
    details: {
      physiological: JSON.parse(JSON.stringify(physiologicalItems)),
      psychological: JSON.parse(JSON.stringify(psychologicalItems)),
      lifestyle: JSON.parse(JSON.stringify(lifestyleItems)),
      physical: JSON.parse(JSON.stringify(physicalItems)),
      social: JSON.parse(JSON.stringify(socialItems))
    }
  }
  
  // 保存到本地存储
  const assessments = uni.getStorageSync('healthAssessments') || []
  assessments.push(assessmentData)
  uni.setStorageSync('healthAssessments', assessments)
  
  uni.showToast({
    title: '保存成功',
    icon: 'success'
  })
  
  // 跳转到结果页
  setTimeout(() => {
    uni.navigateTo({
      url: '/pages/health-guide/assessment-results'
    })
  }, 1500)
}

function goToUpgrade() {
  showUpgradePrompt.value = false
  uni.navigateTo({
    url: '/pages/mine/membership'
  })
}

function closeUpgradePrompt() {
  showUpgradePrompt.value = false
}
</script>

<template>
  <view class="container">
    <view class="header">
      <view class="title">中医健康综合评估</view>
      <view class="subtitle">全面评估您的健康状况</view>
    </view>
    
    <view class="assessment-progress">
      <view class="progress-header">
        <text class="progress-title">评估进度</text>
        <text class="progress-percentage">{{ Math.round((totalScore.value / maxScore.value) * 100) || 0 }}%</text>
      </view>
      
      <view class="progress-bar">
        <view 
          class="progress-inner" 
          :style="{ width: `${Math.round((totalScore.value / maxScore.value) * 100) || 0}%` }"
        ></view>
      </view>
      
      <view class="category-progress">
        <view 
          v-for="category in assessmentCategories" 
          :key="category.id"
          class="category-item"
          :class="{ 'completed': assessmentResults[category.id].completed }"
        >
          <text class="category-name">{{ category.name }}</text>
          <text class="category-status">{{ assessmentResults[category.id].completed ? '完成' : '未完成' }}</text>
        </view>
      </view>
    </view>
    
    <view class="assessment-container">
      <scroll-view class="category-tabs" scroll-x>
        <view 
          v-for="category in assessmentCategories" 
          :key="category.id"
          class="category-tab"
          :class="{ 'active': currentCategory === category.id }"
          @tap="switchCategory(category.id)"
        >
          {{ category.name }}
        </view>
      </scroll-view>
      
      <view class="assessment-items">
        <view 
          v-for="item in assessmentItems[currentCategory]" 
          :key="item.id"
          class="assessment-item"
        >
          <view class="item-header">
            <text class="item-name">{{ item.name }}</text>
            <text class="item-score">{{ item.score }}分</text>
          </view>
          
          <text class="item-description">{{ item.description }}</text>
          
          <view class="score-options">
            <view 
              v-for="option in scoreOptions" 
              :key="option.value"
              class="score-option"
              :class="{ 'selected': item.score === option.value }"
              @tap="updateScore(currentCategory, item.id, option.value)"
            >
              {{ option.label }}
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <view class="footer">
      <view class="total-score">
        <text>总评分：</text>
        <text class="score-value">{{ totalScore }}/{{ maxScore }}</text>
      </view>
      
      <view v-if="assessmentLevel" class="assessment-level">
        <text>健康等级：</text>
        <text 
          class="level-value"
          :class="{
            'excellent': assessmentLevel === '优秀',
            'good': assessmentLevel === '良好',
            'average': assessmentLevel === '中等',
            'fair': assessmentLevel === '一般',
            'poor': assessmentLevel === '需要改善'
          }"
        >
          {{ assessmentLevel }}
        </text>
      </view>
      
      <button class="save-btn" @tap="saveAssessmentResults">保存评估结果</button>
    </view>
    
    <!-- 会员升级提示 -->
    <view v-if="showUpgradePrompt" class="modal-overlay">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">会员功能</text>
          <text class="modal-close" @tap="closeUpgradePrompt">×</text>
        </view>
        
        <view class="upgrade-content">
          <text class="upgrade-title">中医健康综合评估</text>
          <text class="upgrade-desc">完整的健康评估功能需要升级到标准会员或高级会员</text>
          <text class="upgrade-info">当前仅展示部分基础评估功能</text>
        </view>
        
        <view class="modal-footer">
          <button class="cancel-btn" @tap="closeUpgradePrompt">继续使用基础版</button>
          <button class="confirm-btn" @tap="goToUpgrade">升级会员</button>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  margin-bottom: 30rpx;
  
  .title {
    font-size: 40rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
  }
  
  .subtitle {
    font-size: 28rpx;
    color: #666;
  }
}

.assessment-progress {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  
  .progress-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15rpx;
    
    .progress-title {
      font-size: 30rpx;
      font-weight: bold;
      color: #333;
    }
    
    .progress-percentage {
      font-size: 28rpx;
      color: #1890ff;
      font-weight: bold;
    }
  }
  
  .progress-bar {
    height: 16rpx;
    background-color: #f0f0f0;
    border-radius: 8rpx;
    overflow: hidden;
    margin-bottom: 20rpx;
    
    .progress-inner {
      height: 100%;
      background-color: #1890ff;
      border-radius: 8rpx;
      transition: width 0.3s;
    }
  }
  
  .category-progress {
    margin-top: 20rpx;
    
    .category-item {
      display: flex;
      justify-content: space-between;
      padding: 15rpx 0;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      &.completed {
        .category-name {
          color: #333;
        }
        
        .category-status {
          color: #52c41a;
        }
      }
      
      .category-name {
        font-size: 26rpx;
        color: #666;
      }
      
      .category-status {
        font-size: 26rpx;
        color: #999;
      }
    }
  }
}

.assessment-container {
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
  
  .category-tabs {
    display: flex;
    padding: 0 20rpx;
    border-bottom: 1px solid #f0f0f0;
    white-space: nowrap;
    
    .category-tab {
      display: inline-block;
      padding: 24rpx 30rpx;
      font-size: 28rpx;
      color: #666;
      position: relative;
      
      &.active {
        color: #1890ff;
        font-weight: bold;
        
        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 30rpx;
          right: 30rpx;
          height: 4rpx;
          background-color: #1890ff;
          border-radius: 2rpx;
        }
      }
    }
  }
  
  .assessment-items {
    padding: 20rpx 30rpx;
    
    .assessment-item {
      margin-bottom: 40rpx;
      padding-bottom: 30rpx;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        margin-bottom: 0;
        border-bottom: none;
      }
      
      .item-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15rpx;
        
        .item-name {
          font-size: 30rpx;
          font-weight: bold;
          color: #333;
        }
        
        .item-score {
          font-size: 28rpx;
          color: #1890ff;
          font-weight: bold;
        }
      }
      
      .item-description {
        font-size: 26rpx;
        color: #666;
        margin-bottom: 20rpx;
        display: block;
      }
      
      .score-options {
        display: flex;
        flex-wrap: wrap;
        
        .score-option {
          padding: 12rpx 20rpx;
          border: 1px solid #ddd;
          border-radius: 30rpx;
          margin-right: 20rpx;
          margin-bottom: 15rpx;
          font-size: 26rpx;
          color: #666;
          
          &.selected {
            background-color: #1890ff;
            color: #fff;
            border-color: #1890ff;
          }
        }
      }
    }
  }
}

.footer {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  
  .total-score, .assessment-level {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    font-size: 28rpx;
    color: #333;
    
    .score-value, .level-value {
      font-weight: bold;
      margin-left: 10rpx;
    }
    
    .level-value {
      &.excellent {
        color: #52c41a;
      }
      
      &.good {
        color: #1890ff;
      }
      
      &.average {
        color: #faad14;
      }
      
      &.fair {
        color: #fa8c16;
      }
      
      &.poor {
        color: #f5222d;
      }
    }
  }
  
  .save-btn {
    width: 100%;
    height: 80rpx;
    background-color: #1890ff;
    color: #fff;
    font-size: 28rpx;
    border-radius: 40rpx;
    margin-top: 20rpx;
  }
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-content {
  width: 85%;
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  
  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .modal-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .modal-close {
      font-size: 40rpx;
      color: #999;
      padding: 0 10rpx;
    }
  }
  
  .upgrade-content {
    padding: 30rpx 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    
    .upgrade-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 15rpx;
    }
    
    .upgrade-desc {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 15rpx;
    }
    
    .upgrade-info {
      font-size: 26rpx;
      color: #999;
    }
  }
  
  .modal-footer {
    display: flex;
    justify-content: center;
    margin-top: 30rpx;
    
    button {
      height: 80rpx;
      border-radius: 40rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      
      &.cancel-btn {
        flex: 1;
        background-color: #f5f5f5;
        color: #666;
        margin-right: 20rpx;
      }
      
      &.confirm-btn {
        flex: 1;
        background-color: #1890ff;
        color: #fff;
      }
    }
  }
}
</style> 